<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="登记时间" prop="registerTime">
        <el-date-picker
          v-model="queryParams.registerTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="店铺" prop="shopId">
        <select-basic-shop v-model="queryParams.shopId" class="!w-240px"/>
      </el-form-item>
      <el-form-item label="返款日期" prop="refundTime">
        <el-date-picker
          v-model="queryParams.refundTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择类型"
          clearable
          class="!w-240px"
        >
          <el-option value="礼品单"/>
          <el-option value="佣金单"/>
        </el-select>
      </el-form-item>

      <el-form-item label="订单号" prop="oId">
        <el-input
          v-model="queryParams.oId"
          placeholder="请输入订单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="queryParams.remark"
          placeholder="请输入备注"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px"/>
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px"/>
          重置
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['operation:business:create']"
        >
          <Icon icon="ep:plus" class="mr-5px"/>
          新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['operation:business:export']"
        >
          <Icon icon="ep:download" class="mr-5px"/>
          导出
        </el-button>
        <!--        <el-button-->
        <!--            type="danger"-->
        <!--            plain-->
        <!--            :disabled="isEmpty(checkedIds)"-->
        <!--            @click="handleDeleteBatch"-->
        <!--            v-hasPermi="['operation:business:delete']"-->
        <!--        >-->
        <!--          <Icon icon="ep:delete" class="mr-5px"/>-->
        <!--          批量删除-->
        <!--        </el-button>-->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <vxe-toolbar ref="operationBusinessToolbarRef" custom>
      <template #buttons>
        <span></span>
      </template>
    </vxe-toolbar>
    <vxe-table
      id="operationBusinessTableRef"
      ref="operationBusinessTableRef"
      :loading="loading"
      :data="list"
      :row-config="{keyField: 'id'}"
      :column-config="{resizable: true}"
      :checkbox-config="{checkField: 'checked'}"
      :scroll-y="{enabled: true}"
      :custom-config="{storage: true}"
      border
      stripe
      show-overflow
      show-footer
      :footer-method="footerMethod"
      @checkbox-change="handleCheckboxChange"
      @checkbox-all="handleCheckboxChange"
    >
      <vxe-column type="checkbox" width="60" fixed="left"/>
      <vxe-column title="操作" align="center" width="120" fixed="left">
        <template #default="{ row }">
          <el-button
            link
            type="primary"
            @click="openForm('update', row.id)"
            v-hasPermi="['operation:business:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(row.id)"
            v-hasPermi="['operation:business:delete']"
          >
            删除
          </el-button>
        </template>
      </vxe-column>
      <!--      <vxe-column field="id" title="编号" align="center"/>-->
      <vxe-column
        field="registerTime"
        title="登记时间"
        align="center"
        width="180"
        :formatter="({ cellValue }) => dateFormatter2(null, null, cellValue)"
      />
      <vxe-column field="shopId_dictText" title="店铺" align="center" width="180"/>
      <vxe-column
        field="refundTime"
        title="返款日期"
        align="center"
        width="180"
        :formatter="({ cellValue }) => dateFormatter2(null, null, cellValue)"
      />
      <vxe-column field="type" title="类型" align="center"/>
      <vxe-column field="refundMoney" title="返款金额" align="center"/>
      <vxe-column field="orderMoney" title="订单金额" align="center"/>
      <vxe-column field="businessMoney" title="佣金金额" align="center"/>
      <vxe-column field="giftCost" title="礼品成本" align="center"/>
      <vxe-column field="oId" title="订单号" align="center" width="200"/>
      <vxe-column field="remark" title="备注" align="center" min-width="60"/>
      <vxe-column field="creator_dictText" title="创建人" align="center"/>
      <vxe-column
        field="createTime"
        title="创建时间"
        align="center"
        width="180"
        :formatter="({ cellValue }) => dateFormatter(null, null, cellValue)"
      />
    </vxe-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      :page-sizes="[10,  50, 100,500,1000,2000,5000,10000]"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <BusinessForm ref="formRef" @success="getList"/>
</template>

<script setup lang="ts">
import {dateFormatter, dateFormatter2} from '@/utils/formatTime'
import download from '@/utils/download'
import {Business, BusinessApi} from '@/api/business/operation/business/order'
import BusinessForm from './BusinessForm.vue'
import {useUserStore} from "@/store/modules/user";
import {hasPermission} from "@/directives/permission/hasPermi";
import {erpPriceInputFormatter, getSumValue} from "@/utils";
import type {VxeTableInstance, VxeToolbarInstance} from 'vxe-table'

const userStore = useUserStore()


/** 业务-运营-补单 列表 */
defineOptions({name: 'OperationBusiness'})

const message = useMessage() // 消息弹窗
const {t} = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<Business[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  registerTime: [],
  shopId: undefined,
  refundTime: [],
  type: undefined,
  refundMoney: undefined,
  orderMoney: undefined,
  businessMoney: undefined,
  giftCost: undefined,
  oId: undefined,
  remark: undefined,
  createTime: [],
  shopIds: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const operationBusinessTableRef = ref<VxeTableInstance>() // 表格实例
const operationBusinessToolbarRef = ref<VxeToolbarInstance>() // 工具栏实例

/** 初始化 Toolbar 和 Table 关联 **/
onMounted(async () => {
  // 手动将表格和工具栏进行关联
  const $table = operationBusinessTableRef.value
  const $toolbar = operationBusinessToolbarRef.value
  if ($table && $toolbar) {
    $table.connect($toolbar)
  }
  await getList()
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  if (!hasPermission(['operation:business:admin'])) {
    let shopIds = userStore.user.shopIds
    // 检查shopIds是否为空（包括null、undefined、空字符串、纯空格）
    if (!shopIds || typeof shopIds !== 'string' || shopIds.trim() === '') {
      // 为空时弹出错误提示
      message.error('请先进行店铺授权');
      return; // 终止后续逻辑，避免继续执行
    } else {
      // 将字符串按逗号分割为数组，并转换为数字类型（根据需要选择是否转换）
      queryParams.shopIds = shopIds
        .split(',')
        .filter(shopId => shopId.trim() !== '') // 过滤空值
        .map(shopId => {
          // 这里根据实际需求决定是保留字符串还是转为数字
          const num = Number(shopId);
          return isNaN(num) ? shopId : num; // 转换为数字，转换失败则保留原字符串
        });
    }
  }
  try {
    const data = await BusinessApi.getBusinessPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await BusinessApi.deleteBusiness(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {
  }
}

/** 批量删除业务-运营-补单 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await BusinessApi.deleteBusinessList(checkedIds.value);
    checkedIds.value = [];
    message.success(t('common.delSuccess'))
    await getList();
  } catch {
  }
}

const checkedIds = ref<number[]>([])

/** VXE Table 复选框事件 */
const handleCheckboxChange = () => {
  const records = operationBusinessTableRef.value?.getCheckboxRecords() || []
  checkedIds.value = records.map((item) => item.id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await BusinessApi.exportBusiness(queryParams)
    download.excel(data, '业务-运营-补单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** VXE Table 表尾合计方法 */
const footerMethod = ({ columns, data }: any) => {
  return [
    columns.map((column: any, columnIndex: number) => {
      if (columnIndex === 0) {
        return '合计'
      }
      if (['refundMoney', 'orderMoney', 'businessMoney', 'giftCost'].includes(column.field)) {
        const sum = getSumValue(data.map((item: any) => Number(item[column.field])))
        return erpPriceInputFormatter(sum)
      }
      return ''
    })
  ]
}


</script>
